<?php
/**
 * Created by PhpStorm.
 * User: 9ey
 * Date: 2019/5/19
 * Time: 18:07
 */

namespace App\Utils;


class Encryption
{
    /**
     * AES 加密标记
     * @var string
     */
    private $cipher = 'AES-256-ECB';

    /** AES 加密 key
     * @var string
     */
    private $key = 'x945o8gkusdcz6pa2efwmrhnj7lb3vyi';

    /**
     * 解密
     * @param $encryptText
     * @return bool|string
     */
    public static function decode($encryptText)
    {
        $in = new self();
        return $in->decrypt($encryptText);
    }

    /**
     * 加密
     * @param $input
     * @return string
     */
    public static function encode($input)
    {
        $in = new self();
        return $in->encrypt($input);
    }

    /**
     * 加密
     * @param $input
     * @return string
     */
    public function encrypt($input)
    {
        $sign = openssl_encrypt($input, $this->cipher, $this->key, OPENSSL_RAW_DATA);
        return self::str2hex($sign);
    }

    /**
     * 解密
     * @param $encryptText
     * @return bool|string
     */
    public function decrypt($encryptText)
    {
        $decryptedText = self::hex2str($encryptText);
        return openssl_decrypt($decryptedText, $this->cipher, $this->key, OPENSSL_RAW_DATA);
    }

    /**
     * string to hex
     * @param string $str
     * @return string
     */
    private function str2hex($str)
    {
        $hex = '';
        for ($i = 0; $i < strlen($str); $i++) {
            $hexTmp = dechex(ord($str[$i]));
            if (strlen($hexTmp) < 2) {
                $hexTmp = str_pad($hexTmp, 2, '0', STR_PAD_LEFT);
            }
            $hex .= $hexTmp;
        }
        return $hex;
    }

    /**
     * hex to string
     * @param string $hexStr
     * @return string
     */
    private static function hex2str($hexStr)
    {
        $str = '';
        for ($i = 0; $i < strlen($hexStr) - 1; $i += 2) {
            $str .= chr(hexdec($hexStr[$i] . $hexStr[$i + 1]));
        }
        return $str;
    }
}